package com.dommettj.rawfix.settings;

import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class FileBasedSettings implements Settings {

    private static final Logger logger = Logger.getLogger(FileBasedSettings.class);

    private static final String HOST_PROPERTY = "host";
    private static final String PORT_PROPERTY = "port";
    private static final String SENDER_PROPERTY = "senderCompId";
    private static final String TARGET_PROPERTY = "targetCompId";
    private final FileProvider fileProvider;
    private final Properties properties;
    private final String settingsFileName;

    public FileBasedSettings(final FileProvider fileProvider, final String settingsFileName) throws IOException {

        this.fileProvider = fileProvider;
        this.settingsFileName = settingsFileName;

        properties = new Properties();
        properties.load(new FileInputStream(fileProvider.getFileForReading(settingsFileName)));
    }

    @Override
    public String loadHost() {
        return properties.getProperty(HOST_PROPERTY);
    }

    @Override
    public String loadPort() {
        return properties.getProperty(PORT_PROPERTY);
    }

    @Override
    public String loadSenderCompId() {
        return properties.getProperty(SENDER_PROPERTY);
    }

    @Override
    public String loadTargetCompId() {
        return properties.getProperty(TARGET_PROPERTY);
    }

    @Override
    public void save(String host, String port, String senderCompId, String targetCompId) {
        properties.setProperty(HOST_PROPERTY, host);
        properties.setProperty(PORT_PROPERTY, port);
        properties.setProperty(SENDER_PROPERTY, senderCompId);
        properties.setProperty(TARGET_PROPERTY, targetCompId);
        savePropertiesToFile();
    }

    private void savePropertiesToFile() {

        try {
            properties.store(new FileOutputStream(fileProvider.getFileForWriting(settingsFileName)), null);
        } catch (IOException e) {
            logger.error("Failed to savePropertiesToFile settings", e);
        }
    }


}
